package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper,Sku> implements SkuService {
    private static final String DEDUCT_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.deductStock";
    @Override
    @Transactional
    public void deductStock(Map<Long, Integer> cartMap) {
//        for (Map.Entry<Long, Integer> longIntegerEntry : cartMap.entrySet()) {
//            Long skuId = longIntegerEntry.getKey();
//            Integer num = longIntegerEntry.getValue();
//            Sku byId = getById(skuId);
//            if (byId.getStock()<num){
//                throw new LyException(400,"库存不足");
//            }
//            HashMap<String, Object> map = new HashMap<>();
//            map.put("id",skuId);
//            map.put("num",num);
//            getBaseMapper().deductStock(map);
//        }
        //上面有线程安全问题
        executeBatch(sqlSession -> {
            for (Map.Entry<Long, Integer> longIntegerEntry : cartMap.entrySet()) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("id", longIntegerEntry.getKey());
                map.put("num", longIntegerEntry.getValue());
                // 编译statement，namespace.statementId
                sqlSession.update(DEDUCT_STOCK_STATEMENT, map);
            }
            sqlSession.flushStatements();
        });
    }
}
